﻿using BaifudataPay.Applib;
using Com.Allscore;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BaifudataPay
{
    public partial class notifyRSA : System.Web.UI.Page
    {
        #region 商银信通知消息
        protected string notifyId = string.Empty;       //通知ID        
        protected string notifyTime = string.Empty;     //通知时间 （通知时间，格式： YYYYMMDDhhmmss）
        protected string sign = string.Empty;           //签名｛目前支持CA数字证书签名｝
        protected string outOrderId = string.Empty;     //外部交易号｛该交易在合作伙伴系统的流水号｝
        protected string outAcctId = string.Empty;      //外部账户ID ｛搜房网账户ID｝
        protected string subject = string.Empty;        //商品名称｛商品的标题｝
        protected string body = string.Empty;           //商品描述｛商品的具体描述｝
        protected string transAmt = string.Empty;       //交易金额｛交易的总金额，单位为元｝
        protected string tradeStatus = string.Empty;    //交易状态｛ 2表示交易成功，1表示交易失败｝
        protected string merchantId = string.Empty;     //商户号｛合作商户的商户号，由商银信公司分配｝
        protected string terminalId = string.Empty;     //终端号｛合作商户的终端号，终端号不同，费率可能不通｝
        protected string localOrderId = string.Empty;   //商银信交易号｛商银信系统该订单的交易号｝
        protected string transTime = string.Empty;      //交易创建时间｛该笔交易创建的时间｝
        #endregion
        protected void Page_Load(object sender, EventArgs e)
        {
            #region 接收参数
            SortedDictionary<string, string> sPara = GetRequestPost();
            /**notifyId = "453894";Request.Form[
            notifyTime = "20140327133222";
            sign = "MIIKzAYJKoZIhvcNAQcCoIIKvTCCCrkCAQExCzAJBgUrDgMCGgUAMAsGCSqGSIb3DQEHAaCCCNkwggRGMIIDLqADAgECAhQxfHhnSFk7+hmwBilbrBnnbkdVdTANBgkqhkiG9w0BAQUFADB7MQswCQYDVQQGEwJDTjETMBEGA1UECgwKaVRydXNDaGluYTEcMBoGA1UECwwTQ2hpbmEgVHJ1c3QgTmV0d29yazE5MDcGA1UEAwwwaVRydXNDaGluYSBDbGFzcyAyIEVudGVycHJpc2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sNZeFfVQY8Yeq31vlaL/8hAM5PUxLK5Tvh/d8Y3kIoo/pS/uqy/7bqc2J3OiDVjzFHdHNoXJ078FjCDBiO5ViSONUjxzQNWQIuZIBvvkHgr2+POIyLelWhoTRTM0aPVg0R+NWasjcOTrDrtD9bicO9fEKCDBHP3Lt3A3T8djo39FQdgPFfwtvCLX/i6VKSh5JE8D0=";
            outOrderId = "20140327133101";
            outAcctId = "lidong";
            subject = "shangpinmingcheng商品名称";
            body = "shangpinmiaoshu商品描述";
            transAmt = "5000";
            tradeStatus = "2";
            merchantId = "888110000180054";
            terminalId = "53110040";
            localOrderId = "453890";
            transTime = "20140327133115";**/
            #endregion
            /**
                #region 把接收到参数打包成数组
                SortedDictionary<string, string> sPara = new SortedDictionary<string, string>();
                sPara.Add("notifyId", notifyId);
                sPara.Add("notifyTime", notifyTime);
                sPara.Add("sign", sign);
                sPara.Add("outOrderId", outOrderId);
                sPara.Add("outAcctId", outAcctId);
                sPara.Add("subject", subject);
                sPara.Add("body", body);
                sPara.Add("transAmt", transAmt);
                sPara.Add("tradeStatus", tradeStatus);
                sPara.Add("merchantId", merchantId);
                sPara.Add("terminalId", terminalId);
                sPara.Add("localOrderId", localOrderId);
                sPara.Add("transTime", transTime);
                #endregion
            **/

            LogUtil.Instance.WriteInfo("[notifyRSA.aspx] 回调通知页面了。。。");

            if (sPara.Count > 0)//判断是否有带返回参数
            {
                Notify allscoreNotify = new Notify();

                string plainTextO = allscoreNotify.GetPreSignStr(sPara);
                string mysign = Request.Form["sign"];
                
                bool verifyResult = allscoreNotify.VerifyRSA(plainTextO, mysign, Request.Form["inputCharset"]);

                // 日志
                LogUtil.Instance.WriteInfo(string.Format("[notifyRSA.aspx] VerifyRSA: verifyResult={0}, plainTextO = {1}", verifyResult, plainTextO));

                // 服务器通知商户的地址 http://192.168.9.20:8010/olgateway/noticeQuery.htm
                string notifyURL = "http://baifupay.34537.com/BizTest/noticeQueryBizTest.aspx?"
                                     + "merchantId="
                                     + Request.Form["merchantId"]
                                     + "&notifyId="
                                     + Request.Form["notifyId"];

                string result = getNotifyData(notifyURL); // 商户返回"true"

                // 日志
                LogUtil.Instance.WriteInfo(string.Format("[notifyRSA.aspx] getNotifyData: result={0}, notifyURL = {1}", result, notifyURL));

                if (verifyResult && result == "true")//验证成功
                {
                    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                    //请在这里加上商户的业务逻辑程序代码

                    //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
                    //获取商银信的通知返回参数，可参考技术文档中服务器异步通知参数列表

                    string out_trade_no = Request.Form["outOrderId"];   //获取订单号
                    string out_AcctId = Request.Form["outAcctId"];      //获取账号

                    if (Request.Form["tradeStatus"] == "2")
                    {
                        //判断该笔订单是否在商户网站中已经做过处理
                        //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                        //如果有做过处理，不执行商户的业务程序

                        Response.Write("success");  //请不要修改或删除

                    }
                    else
                    {
                        Response.Write("success");  //其他状态判断。普通即时到帐中，其他状态不用判断，直接打印success。

                    }

                    //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

                    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                }
                else//验证失败
                {
                    Response.Write("fail");
                }
            }
            else
            {
                Response.Write("无通知参数");
            }
            Response.End();
        }
        public string getNotifyData(string url)
        {
            try
            {
                WebClient wc = new WebClient();
                Stream stream = wc.OpenRead(url);
                StreamReader reader = new StreamReader(stream);
                string reault = reader.ReadToEnd();

                return reault;
            }
            catch (Exception e)
            {
                return null;
            }

        }
        /// <summary>
        /// 获取商银信POST过来通知消息，并以“参数名=参数值”的形式组成数组
        /// </summary>
        /// <returns>request回来的信息组成的数组</returns>
        public SortedDictionary<string, string> GetRequestPost()
        {
            int i = 0;
            SortedDictionary<string, string> sArray = new SortedDictionary<string, string>();
            NameValueCollection coll;
            //Load Form variables into NameValueCollection variable.
            coll = Request.Form;

            // Get names of all forms into a string array.
            String[] requestItem = coll.AllKeys;

            for (i = 0; i < requestItem.Length; i++)
            {
                sArray.Add(requestItem[i], Request.Form[requestItem[i]]);
            }
            return sArray;
        }
    }
}